package com.tanhua.server;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dto.RecommendUserDto;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.interceptor.UserHolder;
import com.tanhua.model.UserInfo;
import com.tanhua.mondb.RecommendUser;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    /*
    查询今日今日佳人
    */
    public TodayBest  todayBest() {
        Long userId = UserHolder.getUserId();
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if(recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99d);
        }
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        return  vo;
    }
    /*
    * 推荐列表
    * */
    public PageResult recommendation(RecommendUserDto dto) {
        Long userId = UserHolder.getUserId();
        PageResult pr  = recommendUserApi.queryRecommendationUserList(dto.getPage(),dto.getPagesize(),userId);
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        if(items==null){
            return  pr;
        }
       /* ArrayList<TodayBest> list = new ArrayList<>();
        for (RecommendUser item :items){
            Long recommendUserId = item.getUserId();
            UserInfo userInfo = userInfoApi.findById(recommendUserId);
            if(userInfo != null){
                if(!StringUtils.isEmpty(dto.getGender())&& !dto.getGender().equals(userInfo.getGender())){
                    continue;
                }
                if(dto.getAge()!=null && dto.getAge()<userInfo.getAge()){
                    continue;
                }
                TodayBest vo = TodayBest.init(userInfo, item);
                list.add(vo);
            }
        }*/
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());

        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
        ArrayList<TodayBest> list = new ArrayList<>();
        for(RecommendUser item:items){
            UserInfo info = map.get(item.getUserId());
            if(info!=null){
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        pr.setItems(list);
        return pr;
    }
}
